﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using BeatEmUp.Menu;
using BeatEmUp.Characters.Enemies;
using BeatEmUp.HUD;
using BeatEmUp.Items.Weapons;
using BeatEmUp.Enums;
using Microsoft.Xna.Framework.Content;
using System.Diagnostics;

namespace BeatEmUp.World
{
    public class Config<T> where T : Element
    {
        protected GameManager gameManager;

        public List<T> Elements
        {
            private set;
            get;
        }

        public List<T> CurrentElements
        {
            private set;
            get;
        }

        public Config(GameManager gameManager, T[] elements)
        {
            this.gameManager = gameManager;
            this.Elements = new List<T>(elements);
        }

        public void LoadContent(ContentManager content)
        {
            foreach (T element in this.Elements)
            {
                element.LoadContent(content);
            }
        }

        public bool CanScroll(int to, int gameWidth)
        {
            T lastElement = this.Elements.Last();

            return (to + gameWidth) <= (lastElement.AbsolutePosition.X + lastElement.Size.X);
        }

        public void DesignateCurrentElements(Viewport viewport, Direction direction)
        {
            this.CurrentElements = new List<T>();
            Vector2 elementRelativePosition;

            if (Direction.Left == direction)
                throw new Exception("Not supported");

            int i = -1;
            foreach (T element in this.Elements)
            {
                ++i;
                elementRelativePosition =  element.GetRelativePosition(viewport.WorldPosition);

                if ((elementRelativePosition.X + element.Size.X) >= 0 && elementRelativePosition.X <= viewport.GameWidth)
                {
                    this.CurrentElements.Add(element);
                }
            }

            this.CurrentElements.Sort(new ByDepthSorter());
        }

        private class ByDepthSorter : IComparer<T>
        {
            public int Compare(T x, T y)
            {
                if (x.Depth == y.Depth)
                    return 0;

                return (x.Depth> y.Depth) ? 1 : -1;
            }
        }
    }
}
